/**
 * @description render elem
 * @author Ling
 * @date 2024-08-08
 */

import { h, VNode } from 'snabbdom';
import { DomEditor, IDomEditor, SlateElement } from '@wangeditor/editor';
import { LinkCardElement } from '../custom-types';

function renderLinkCard(elem: SlateElement, children: VNode[] | null, editor: IDomEditor): VNode {
  const selected = DomEditor.isNodeSelected(editor, elem); // 当前节点是否选中
  let { title, link, articleId, linkType ,target} = elem as LinkCardElement;
  if (!linkType && target) {
    // 遍历target
    linkType = target.includes('article') ? 'article' : 'link';
    articleId = target.split('_')[1];
  }

  // 文字部分
  const infoVnode = h(
    'a',
    {
      props: {
        className: 'w-e-textarea-link-card-text-content',
      },
      on: {
        mousedown: (event) => event.preventDefault(),// 阻止默认行为
        click: (event) => { // 添加 click 事件处理器
          event.preventDefault(); // 阻止默认行为
        },
      }, 
    },
    [
      h('div', { className: 'w-e-textarea-link-card-title' }, title),
      h(
        'div',
        { className: 'w-e-textarea-link-card-text' },
        `${(linkType === 'article' || articleId) ? `文章ID: ${articleId}` : link}`,
      ),
    ],
  );

  // 容器
  const vnode = h(
    'div',
    {
      props: {
        contentEditable: false,
        className: 'w-e-textarea-link-card-container',
      },
      dataset: {
        selected: selected ? 'true' : '', // 标记为 选中
      },
      on: {
        mousedown: (event) => event.preventDefault(),
      },
    },
    [infoVnode],
  );
// console.log('生成的卡片：', vnode)
  return vnode;
}

const conf = {
  type: 'link-card', // 节点 type ，重要！！！
  renderElem: renderLinkCard,
};

export default conf;
